//package jd.se.base;
//
//import jd.se.common.CurrentUser;
//import jd.se.common.Result;
//import jd.se.common.Utils;
//
//import javax.servlet.*;
//import javax.servlet.annotation.WebFilter;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
//import java.io.IOException;
//
//@WebFilter("/*")
//public class SecurityFilter implements Filter {
//
//    private static final String[] freePaths = {"/login.html","/login","/index.html","/findpw.html","/register.html","/register"};
//    private static final String[] freePrefixPaths = {"/css","/fonts","/images","/js","/layer","/img"};
//
//    private static boolean isFreePath(String thePath){
//        for(String path:freePaths){
//            if(path.equals(thePath)){
//                return true;
//            }
//        }
//        return false;
//    }
//
//    private static boolean hasPrefix(String thePath){
//        for(int i=0;i<freePrefixPaths.length;i++){
//            if(thePath.startsWith(freePrefixPaths[i])){
//                return true;
//            }
//        }
//        return false;
//    }
//
//    private static boolean isAjax(HttpServletRequest req){
//       return "XMLHttpRequest".equals(req.getHeader("X-Requested-With"));
//
//    }
//
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//
//    }
//
//    @Override
//    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//
//        HttpServletRequest req = (HttpServletRequest)request;
//        HttpServletResponse resp = (HttpServletResponse) response;
//
//
//        resp.setHeader("Cache-control", "no-cache no-store must-revalidate");
//        resp.setHeader("pragma", "no-cache");
//        resp.setDateHeader("expires", -1);
//
//        String path = req.getServletPath();
//
//        if(isFreePath(path) || hasPrefix(path)){
//            chain.doFilter(request,response);
//            return;
//        }
//
//        String method = req.getMethod();// GET、POST、options等等（options请求是预检请求，在post等发送前发送，用于检查接口是否可用）
//        if(method.equalsIgnoreCase("options")){
//            chain.doFilter(request,response);
//            return;
//        }
//
//        HttpSession session = req.getSession();
//        if(session.getAttribute(CurrentUser.SESSION_ATTR_NAME)!=null){
//            chain.doFilter(request,response);
//            return;
//        }
//
//
//        //不放行:分两种情况，1：ajax一步请求 2：非ajax请求
//
//        if(isAjax(req)){
//            Utils.outResult(resp, Result.fail(Result.ERR_CODE_UNLOGIN, "尚未登录或登录过期！"));
//        }else{
//            //不放行(req.getContextPath() 获取上下文路径如：/jd_demo_server_war_exploded)
//            resp.sendRedirect(req.getContextPath()+"/login.html");
//        }
//
//
//
//
//    }
//
//    @Override
//    public void destroy() {
//
//    }
//}
